package com.example.graduatedesigned.deepseek;

import static com.example.graduatedesigned.deepseek.Config.API_KEY;
import static com.example.graduatedesigned.deepseek.Config.BASE_URL;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


/**
 * @Author: MuMu
 * @Date: 2025/2/6 9:50
 */
public class DeepSeekClient {

    public interface Lis{
        void msg(String msg);
    }

    public void ask(List<RequestMessageItem> requestMessageItemList, boolean  stream, Lis lis) {
        //  创建OkHttp客户端
        OkHttpClient client = new OkHttpClient();

        // 把用户提问添加到请求中
        String requestBody = new RequestBodyParameter("deepseek-chat", requestMessageItemList, stream).toString();
        RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(BASE_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseData = response.body().string();
                        lis.msg(responseData);
                    } catch (Exception e){
                    }
                }
            }
        });
    }

    public String getMsg(String msg){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(msg);
            JSONArray choices = jsonObject.getJSONArray("choices");
            String str = choices.getJSONObject(0).getJSONObject("message").getString("content");
            return str.substring(1, str.length() - 1);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }

}